<template>
  <!-- 主内容区域 -->
  <div class="content-area">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon total">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.totalEquipment }}</div>
              <div class="stat-label">设备总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon warning">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.maintenanceCount }}</div>
              <div class="stat-label">待维护设备</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon expired">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">
                {{ stats.warrantyExpiringCount }}
              </div>
              <div class="stat-label">保修即将到期</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon value">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">
                ¥{{ formatAmount(stats.totalValue) }}
              </div>
              <div class="stat-label">设备总价值</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选卡片 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">设备名称</div>
          <el-input
            v-model="filters.equipmentName"
            placeholder="请输入设备名称"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">设备编号</div>
          <el-input
            v-model="filters.equipmentCode"
            placeholder="请输入设备编号"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">设备类型</div>
          <el-select
            v-model="filters.equipmentType"
            placeholder="请选择设备类型"
            clearable
          >
            <el-option label="诊断设备" value="diagnostic" />
            <el-option label="治疗设备" value="therapeutic" />
            <el-option label="监护设备" value="monitoring" />
            <el-option label="实验室设备" value="laboratory" />
            <el-option label="手术设备" value="surgical" />
            <el-option label="其他设备" value="other" />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">设备状态</div>
          <el-select
            v-model="filters.status"
            placeholder="请选择设备状态"
            clearable
          >
            <el-option label="正常" value="normal" />
            <el-option label="使用中" value="in_use" />
            <el-option label="待维护" value="maintenance" />
            <el-option label="维修中" value="repairing" />
            <el-option label="停用" value="disabled" />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">所属科室</div>
          <el-select
            v-model="filters.department"
            placeholder="请选择所属科室"
            clearable
          >
            <el-option
              v-for="department in departmentOptions"
              :key="department.value"
              :label="department.label"
              :value="department.value"
            />
          </el-select>
        </div>
      </div>
      <div class="action-buttons">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" @click="searchEquipment">查询</el-button>
        <el-button type="success" @click="showAddEquipmentDialog">
          <el-icon><Plus /></el-icon>
          新增设备
        </el-button>
        <el-button type="warning" @click="showMaintenanceDialog">
          <el-icon><Tools /></el-icon>
          维护记录
        </el-button>
        <el-button type="danger" @click="exportEquipment">
          <el-icon><Document /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 设备表格 -->
    <div class="equipment-table">
      <div class="table-header">
        <div class="table-title">设备列表</div>
        <div class="table-tools">
          <el-button type="primary" @click="exportData">
            <el-icon><Download /></el-icon>
            导出Excel
          </el-button>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table :data="equipments" style="width: 100%" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="设备编号" width="120" />
        <el-table-column label="设备信息" min-width="200">
          <template #default="{ row }">
            <div class="equipment-info">
              <div class="equipment-image">
                <el-image
                  :src="row.image"
                  :alt="row.name"
                  fit="cover"
                  style="width: 50px; height: 50px; border-radius: 6px"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
              <div class="equipment-details">
                <div class="equipment-name">{{ row.name }}</div>
                <div class="equipment-model">{{ row.model }}</div>
                <div class="equipment-manufacturer">
                  {{ row.manufacturer }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            {{ formatEquipmentType(row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="department" label="所属科室" width="120">
          <template #default="{ row }">
            {{ formatDepartment(row.department) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="价值" width="120">
          <template #default="{ row }">
            <div class="price-info">¥{{ formatAmount(row.price) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="采购日期" width="120" prop="purchaseDate" />
        <el-table-column label="保修期限" width="120">
          <template #default="{ row }">
            <div :class="['warranty-info', getWarrantyStatusClass(row)]">
              {{ row.warrantyEndDate }}
              <span v-if="isWarrantyExpiringSoon(row)" class="warranty-warning">
                <el-icon><Warning /></el-icon>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="下次维护"
          width="120"
          prop="nextMaintenanceDate"
        />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-cell">
              <el-button size="small" @click="viewEquipmentDetails(row)"
                >详情</el-button
              >
              <el-button
                size="small"
                type="primary"
                @click="editEquipment(row)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="warning"
                @click="recordMaintenance(row)"
              >
                维护
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteEquipment(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 新增/编辑设备对话框 -->
  <el-dialog
    v-model="equipmentDialog.visible"
    :title="equipmentDialog.isEdit ? '编辑设备信息' : '新增设备'"
    width="800px"
  >
    <el-form
      :model="equipmentForm"
      label-width="100px"
      :rules="equipmentRules"
      ref="equipmentFormRef"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备编号" prop="code">
            <el-input
              v-model="equipmentForm.code"
              placeholder="请输入设备编号"
              :disabled="equipmentDialog.isEdit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="name">
            <el-input
              v-model="equipmentForm.name"
              placeholder="请输入设备名称"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备型号" prop="model">
            <el-input
              v-model="equipmentForm.model"
              placeholder="请输入设备型号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备类型" prop="type">
            <el-select
              v-model="equipmentForm.type"
              placeholder="请选择设备类型"
            >
              <el-option label="诊断设备" value="diagnostic" />
              <el-option label="治疗设备" value="therapeutic" />
              <el-option label="监护设备" value="monitoring" />
              <el-option label="实验室设备" value="laboratory" />
              <el-option label="手术设备" value="surgical" />
              <el-option label="其他设备" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生产厂家" prop="manufacturer">
            <el-input
              v-model="equipmentForm.manufacturer"
              placeholder="请输入生产厂家"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属科室" prop="department">
            <el-select
              v-model="equipmentForm.department"
              placeholder="请选择所属科室"
            >
              <el-option
                v-for="department in departmentOptions"
                :key="department.value"
                :label="department.label"
                :value="department.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备价格" prop="price">
            <el-input-number
              v-model="equipmentForm.price"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采购日期" prop="purchaseDate">
            <el-date-picker
              v-model="equipmentForm.purchaseDate"
              type="date"
              placeholder="选择采购日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="保修开始" prop="warrantyStartDate">
            <el-date-picker
              v-model="equipmentForm.warrantyStartDate"
              type="date"
              placeholder="选择保修开始日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="保修结束" prop="warrantyEndDate">
            <el-date-picker
              v-model="equipmentForm.warrantyEndDate"
              type="date"
              placeholder="选择保修结束日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="上次维护" prop="lastMaintenanceDate">
            <el-date-picker
              v-model="equipmentForm.lastMaintenanceDate"
              type="date"
              placeholder="选择上次维护日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="下次维护" prop="nextMaintenanceDate">
            <el-date-picker
              v-model="equipmentForm.nextMaintenanceDate"
              type="date"
              placeholder="选择下次维护日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="设备图片" prop="image">
        <el-upload
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleImageChange"
        >
          <el-button type="primary">选择图片</el-button>
          <template #tip>
            <div class="el-upload__tip">支持 jpg/png 格式，大小不超过 2MB</div>
          </template>
        </el-upload>
        <div v-if="equipmentForm.image" class="image-preview">
          <el-image
            :src="equipmentForm.image"
            style="width: 100px; height: 100px; margin-top: 10px"
            fit="cover"
          />
        </div>
      </el-form-item>

      <el-form-item label="设备状态" prop="status">
        <el-radio-group v-model="equipmentForm.status">
          <el-radio label="normal">正常</el-radio>
          <el-radio label="in_use">使用中</el-radio>
          <el-radio label="maintenance">待维护</el-radio>
          <el-radio label="repairing">维修中</el-radio>
          <el-radio label="disabled">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="设备描述" prop="description">
        <el-input
          v-model="equipmentForm.description"
          type="textarea"
          :rows="3"
          placeholder="请输入设备描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="equipmentDialog.visible = false">取消</el-button>
      <el-button type="primary" @click="submitEquipmentForm">确认</el-button>
    </template>
  </el-dialog>

  <!-- 维护记录对话框 -->
  <el-dialog
    v-model="maintenanceDialog.visible"
    :title="`维护记录 - ${currentEquipment?.name}`"
    width="600px"
  >
    <el-form :model="maintenanceForm" label-width="100px">
      <el-form-item label="设备状态">
        <el-tag :type="getStatusTagType(currentEquipment?.status)" size="small">
          {{ formatStatus(currentEquipment?.status) }}
        </el-tag>
      </el-form-item>
      <el-form-item label="维护类型" prop="maintenanceType">
        <el-radio-group v-model="maintenanceForm.maintenanceType">
          <el-radio label="routine">常规维护</el-radio>
          <el-radio label="repair">故障维修</el-radio>
          <el-radio label="inspection">定期检查</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="维护日期" prop="maintenanceDate">
        <el-date-picker
          v-model="maintenanceForm.maintenanceDate"
          type="date"
          placeholder="选择维护日期"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="维护人员" prop="maintenancePerson">
        <el-input
          v-model="maintenanceForm.maintenancePerson"
          placeholder="请输入维护人员姓名"
        />
      </el-form-item>
      <el-form-item label="维护内容" prop="maintenanceContent">
        <el-input
          v-model="maintenanceForm.maintenanceContent"
          type="textarea"
          :rows="3"
          placeholder="请输入维护内容"
        />
      </el-form-item>
      <el-form-item label="下次维护" prop="nextMaintenanceDate">
        <el-date-picker
          v-model="maintenanceForm.nextMaintenanceDate"
          type="date"
          placeholder="选择下次维护日期"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="备注" prop="notes">
        <el-input
          v-model="maintenanceForm.notes"
          type="textarea"
          :rows="2"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="maintenanceDialog.visible = false">取消</el-button>
      <el-button type="primary" @click="confirmMaintenance">确认记录</el-button>
    </template>
  </el-dialog>

  <!-- 设备详情抽屉 -->
  <el-drawer
    v-model="detailDrawer.visible"
    title="设备详细信息"
    :direction="'rtl'"
    size="40%"
  >
    <div class="equipment-detail" v-if="currentEquipment">
      <div class="detail-header">
        <el-image
          :src="currentEquipment.image"
          style="width: 80px; height: 80px; border-radius: 8px"
          fit="cover"
        >
          <template #error>
            <div class="image-error-large">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
        <div class="equipment-basic">
          <h3>{{ currentEquipment.name }}</h3>
          <p>{{ currentEquipment.model }}</p>
          <el-tag :type="getStatusTagType(currentEquipment.status)">
            {{ formatStatus(currentEquipment.status) }}
          </el-tag>
        </div>
      </div>

      <el-divider />

      <div class="detail-section">
        <h4>基本信息</h4>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="设备编号">{{
            currentEquipment.code
          }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{
            formatEquipmentType(currentEquipment.type)
          }}</el-descriptions-item>
          <el-descriptions-item label="设备型号">{{
            currentEquipment.model
          }}</el-descriptions-item>
          <el-descriptions-item label="生产厂家">{{
            currentEquipment.manufacturer
          }}</el-descriptions-item>
          <el-descriptions-item label="所属科室">{{
            formatDepartment(currentEquipment.department)
          }}</el-descriptions-item>
          <el-descriptions-item label="设备价值"
            >¥{{ formatAmount(currentEquipment.price) }}</el-descriptions-item
          >
        </el-descriptions>
      </div>

      <div class="detail-section">
        <h4>时间信息</h4>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="采购日期">{{
            currentEquipment.purchaseDate
          }}</el-descriptions-item>
          <el-descriptions-item label="保修开始">{{
            currentEquipment.warrantyStartDate
          }}</el-descriptions-item>
          <el-descriptions-item label="保修结束">
            <span :class="getWarrantyStatusClass(currentEquipment)">
              {{ currentEquipment.warrantyEndDate }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="上次维护">{{
            currentEquipment.lastMaintenanceDate || "无记录"
          }}</el-descriptions-item>
          <el-descriptions-item label="下次维护">{{
            currentEquipment.nextMaintenanceDate || "未安排"
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="detail-section" v-if="currentEquipment.description">
        <h4>设备描述</h4>
        <p>{{ currentEquipment.description }}</p>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const sidebarOpen = ref(false);
const router = useRouter();
const store = useStore();

const username = ref(store.state.user?.username || "管理员");
const filters = reactive({
  equipmentName: "",
  equipmentCode: "",
  equipmentType: "",
  status: "",
  department: "",
});

const stats = reactive({
  totalEquipment: 89,
  maintenanceCount: 7,
  warrantyExpiringCount: 5,
  totalValue: 3568000.0,
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 科室选项
const departmentOptions = [
  { value: "D001", label: "内科" },
  { value: "D002", label: "外科" },
  { value: "D003", label: "儿科" },
  { value: "D004", label: "妇产科" },
  { value: "D005", label: "眼科" },
  { value: "D006", label: "耳鼻喉科" },
  { value: "D007", label: "口腔科" },
  { value: "D008", label: "皮肤科" },
  { value: "D009", label: "急诊科" },
  { value: "D010", label: "检验科" },
  { value: "D011", label: "影像科" },
  { value: "D012", label: "药房" },
];

// 设备数据
const equipments = ref([]);

// 设备对话框相关
const equipmentDialog = reactive({
  visible: false,
  isEdit: false,
});

const equipmentForm = reactive({
  code: "",
  name: "",
  model: "",
  type: "diagnostic",
  manufacturer: "",
  department: "",
  price: 0,
  purchaseDate: "",
  warrantyStartDate: "",
  warrantyEndDate: "",
  lastMaintenanceDate: "",
  nextMaintenanceDate: "",
  image: "",
  status: "normal",
  description: "",
});

const equipmentRules = {
  code: [{ required: true, message: "请输入设备编号", trigger: "blur" }],
  name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择设备类型", trigger: "change" }],
  manufacturer: [
    { required: true, message: "请输入生产厂家", trigger: "blur" },
  ],
  department: [
    { required: true, message: "请选择所属科室", trigger: "change" },
  ],
  price: [{ required: true, message: "请输入设备价格", trigger: "blur" }],
  purchaseDate: [
    { required: true, message: "请选择采购日期", trigger: "change" },
  ],
  status: [{ required: true, message: "请选择设备状态", trigger: "change" }],
};

const equipmentFormRef = ref(null);

// 维护记录对话框相关
const maintenanceDialog = reactive({
  visible: false,
});

const maintenanceForm = reactive({
  maintenanceType: "routine",
  maintenanceDate: "",
  maintenancePerson: "",
  maintenanceContent: "",
  nextMaintenanceDate: "",
  notes: "",
});

const currentEquipment = ref(null);

// 详情抽屉相关
const detailDrawer = reactive({
  visible: false,
});

const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value;
};

const resetFilters = () => {
  filters.equipmentName = "";
  filters.equipmentCode = "";
  filters.equipmentType = "";
  filters.status = "";
  filters.department = "";
  loadEquipment();
};

const searchEquipment = () => {
  pagination.currentPage = 1;
  loadEquipment();
};

const loadEquipment = () => {
  // 模拟设备数据
  const mockData = [
    {
      id: "E10001",
      code: "CT-001",
      name: "全身CT扫描仪",
      model: "SOMATOM Scope",
      type: "diagnostic",
      manufacturer: "西门子",
      department: "D011",
      price: 1850000,
      purchaseDate: "2022-05-10",
      warrantyStartDate: "2022-05-15",
      warrantyEndDate: "2025-05-14",
      lastMaintenanceDate: "2023-11-20",
      nextMaintenanceDate: "2024-05-20",
      image: "https://example.com/ct-scanner.jpg",
      status: "normal",
      description: "16排螺旋CT，用于全身各部位检查",
    },
    {
      id: "E10002",
      code: "US-002",
      name: "彩色多普勒超声",
      model: "LOGIQ E10",
      type: "diagnostic",
      manufacturer: "GE医疗",
      department: "D011",
      price: 980000,
      purchaseDate: "2022-08-15",
      warrantyStartDate: "2022-08-20",
      warrantyEndDate: "2024-08-19",
      lastMaintenanceDate: "2023-12-10",
      nextMaintenanceDate: "2024-06-10",
      image: "https://example.com/ultrasound.jpg",
      status: "in_use",
      description: "高端全身应用彩色多普勒超声系统",
    },
    {
      id: "E10003",
      code: "MON-003",
      name: "多参数监护仪",
      model: "IntelliVue MX700",
      type: "monitoring",
      manufacturer: "飞利浦",
      department: "D009",
      price: 85000,
      purchaseDate: "2023-01-20",
      warrantyStartDate: "2023-01-25",
      warrantyEndDate: "2025-01-24",
      lastMaintenanceDate: "2023-07-20",
      nextMaintenanceDate: "2024-01-20",
      image: "https://example.com/monitor.jpg",
      status: "maintenance",
      description: "病人生命体征监测，支持12导联心电图",
    },
    {
      id: "E10004",
      code: "LAB-004",
      name: "全自动生化分析仪",
      model: "Cobas 8000",
      type: "laboratory",
      manufacturer: "罗氏诊断",
      department: "D010",
      price: 1200000,
      purchaseDate: "2021-11-05",
      warrantyStartDate: "2021-11-10",
      warrantyEndDate: "2024-11-09",
      lastMaintenanceDate: "2023-05-15",
      nextMaintenanceDate: "2023-11-15",
      image: "https://example.com/analyzer.jpg",
      status: "repairing",
      description: "高速全自动生化免疫分析系统",
    },
    {
      id: "E10005",
      code: "SUR-005",
      name: "手术无影灯",
      model: "PowerLED 800",
      type: "surgical",
      manufacturer: "迈柯唯",
      department: "D002",
      price: 150000,
      purchaseDate: "2023-03-12",
      warrantyStartDate: "2023-03-17",
      warrantyEndDate: "2026-03-16",
      lastMaintenanceDate: "2023-09-12",
      nextMaintenanceDate: "2024-03-12",
      image: "https://example.com/surgical-light.jpg",
      status: "normal",
      description: "LED手术无影灯，无级调光，色温可调",
    },
  ];

  // 简单的筛选逻辑
  let filteredData = mockData;

  if (filters.equipmentName) {
    filteredData = filteredData.filter((item) =>
      item.name.includes(filters.equipmentName)
    );
  }

  if (filters.equipmentCode) {
    filteredData = filteredData.filter((item) =>
      item.code.includes(filters.equipmentCode)
    );
  }

  if (filters.equipmentType) {
    filteredData = filteredData.filter(
      (item) => item.type === filters.equipmentType
    );
  }

  if (filters.status) {
    filteredData = filteredData.filter(
      (item) => item.status === filters.status
    );
  }

  if (filters.department) {
    filteredData = filteredData.filter(
      (item) => item.department === filters.department
    );
  }

  equipments.value = filteredData;
  pagination.total = filteredData.length;
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
  loadEquipment();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadEquipment();
};

const viewEquipmentDetails = (equipment) => {
  currentEquipment.value = equipment;
  detailDrawer.visible = true;
};

const editEquipment = (equipment) => {
  Object.assign(equipmentForm, equipment);
  equipmentDialog.isEdit = true;
  equipmentDialog.visible = true;
};

const recordMaintenance = (equipment) => {
  currentEquipment.value = equipment;
  Object.assign(maintenanceForm, {
    maintenanceType: "routine",
    maintenanceDate: new Date().toISOString().split("T")[0],
    maintenancePerson: "",
    maintenanceContent: "",
    nextMaintenanceDate: "",
    notes: "",
  });
  maintenanceDialog.visible = true;
};

const deleteEquipment = (equipment) => {
  ElMessageBox.confirm(
    `确定要删除设备 ${equipment.name} 吗？此操作不可恢复！`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      equipments.value = equipments.value.filter((e) => e.id !== equipment.id);
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const showAddEquipmentDialog = () => {
  Object.assign(equipmentForm, {
    code: "",
    name: "",
    model: "",
    type: "diagnostic",
    manufacturer: "",
    department: "",
    price: 0,
    purchaseDate: "",
    warrantyStartDate: "",
    warrantyEndDate: "",
    lastMaintenanceDate: "",
    nextMaintenanceDate: "",
    image: "",
    status: "normal",
    description: "",
  });
  equipmentDialog.isEdit = false;
  equipmentDialog.visible = true;
};

const showMaintenanceDialog = () => {
  ElMessage.info("请选择要记录维护的设备");
};

const handleImageChange = (file) => {
  // 模拟图片上传
  equipmentForm.image = "https://example.com/equipment.jpg";
  ElMessage.success("图片上传成功");
};

const submitEquipmentForm = async () => {
  try {
    await equipmentFormRef.value.validate();

    if (equipmentDialog.isEdit) {
      const index = equipments.value.findIndex(
        (e) => e.id === equipmentForm.id
      );
      if (index !== -1) {
        equipments.value[index] = {
          ...equipmentForm,
        };
      }
      ElMessage.success("设备信息更新成功");
    } else {
      const newEquipment = {
        ...equipmentForm,
        id: `E${equipments.value.length + 10001}`,
      };
      equipments.value.unshift(newEquipment);
      ElMessage.success("设备添加成功");
    }

    equipmentDialog.visible = false;
    loadEquipment();
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

const confirmMaintenance = () => {
  if (!currentEquipment.value) return;

  // 更新设备维护信息
  const equipment = equipments.value.find(
    (e) => e.id === currentEquipment.value.id
  );
  if (equipment) {
    equipment.lastMaintenanceDate = maintenanceForm.maintenanceDate;
    equipment.nextMaintenanceDate = maintenanceForm.nextMaintenanceDate;
    equipment.status = "normal"; // 维护后状态恢复正常
  }

  ElMessage.success("维护记录已保存");
  maintenanceDialog.visible = false;
};

const exportData = () => {
  ElMessage.success("数据导出成功");
};

const exportEquipment = () => {
  ElMessage.success("设备数据导出成功");
};

const refreshData = () => {
  loadEquipment();
  ElMessage.success("数据已刷新");
};

const formatAmount = (amount) => {
  return Number(amount)
    .toFixed(2)
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

const formatEquipmentType = (type) => {
  const typeMap = {
    diagnostic: "诊断设备",
    therapeutic: "治疗设备",
    monitoring: "监护设备",
    laboratory: "实验室设备",
    surgical: "手术设备",
    other: "其他设备",
  };
  return typeMap[type] || type;
};

const formatStatus = (status) => {
  const statusMap = {
    normal: "正常",
    in_use: "使用中",
    maintenance: "待维护",
    repairing: "维修中",
    disabled: "停用",
  };
  return statusMap[status] || status;
};

const formatDepartment = (departmentCode) => {
  const dept = departmentOptions.find((d) => d.value === departmentCode);
  return dept ? dept.label : departmentCode;
};

const getStatusTagType = (status) => {
  const typeMap = {
    normal: "success",
    in_use: "primary",
    maintenance: "warning",
    repairing: "danger",
    disabled: "info",
  };
  return typeMap[status] || "default";
};

const isWarrantyExpiringSoon = (equipment) => {
  if (!equipment.warrantyEndDate) return false;
  const endDate = new Date(equipment.warrantyEndDate);
  const today = new Date();
  const diffTime = endDate.getTime() - today.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays <= 90 && diffDays > 0;
};

const getWarrantyStatusClass = (equipment) => {
  if (!equipment.warrantyEndDate) return "";

  const endDate = new Date(equipment.warrantyEndDate);
  const today = new Date();

  if (endDate < today) return "warranty-expired";
  if (isWarrantyExpiringSoon(equipment)) return "warranty-expiring";
  return "";
};

const logout = () => {
  ElMessageBox.confirm("确定要退出登录吗？", "退出确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      router.push("/login");
      ElMessage.success("已退出登录");
    })
    .catch(() => {
      ElMessage.info("已取消退出");
    });
};

onMounted(() => {
  loadEquipment();
});
</script>

<style lang="scss" scoped>
.content-area {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  height: 0;  // 添加这行
  min-height: 100%;  // 添加这行
  overflow-y: auto;  // 确保有这行
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 16px;
  font-size: 24px;
  color: #fff;
}

.stat-icon.total {
  background: linear-gradient(135deg, #409eff, #79bbff);
}

.stat-icon.warning {
  background: linear-gradient(135deg, #e6a23c, #f3d19e);
}

.stat-icon.expired {
  background: linear-gradient(135deg, #909399, #c8c9cc);
}

.stat-icon.value {
  background: linear-gradient(135deg, #67c23a, #b3e19d);
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.filter-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  flex: 1;
  min-width: 200px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.equipment-table {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-tools {
  display: flex;
  gap: 12px;
}

.equipment-info {
  display: flex;
  align-items: center;
}

.equipment-image {
  margin-right: 12px;
}

.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  background: #f5f7fa;
  border-radius: 6px;
  color: #c0c4cc;
}

.equipment-details {
  flex: 1;
}

.equipment-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.equipment-model,
.equipment-manufacturer {
  font-size: 12px;
  color: #909399;
  margin-bottom: 2px;
}

.price-info {
  font-weight: 500;
  color: #e6a23c;
}

.warranty-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.warranty-expired {
  color: #f56c6c;
}

.warranty-expiring {
  color: #e6a23c;
}

.warranty-warning {
  color: #e6a23c;
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.equipment-detail {
  padding: 0 20px;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.image-error-large {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  background: #f5f7fa;
  border-radius: 8px;
  color: #c0c4cc;
  font-size: 24px;
}

.equipment-basic h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.equipment-basic p {
  margin: 0 0 8px 0;
  color: #606266;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-weight: 500;
}

.image-preview {
  margin-top: 10px;
}

:deep(.el-descriptions__body) {
  background-color: #fafafa;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
}

@media (max-width: 768px) {
  .stats-cards,
  .actions-grid,
  .status-cards {
    grid-template-columns: 1fr;
  }

  .sidebar {
    position: fixed;
    left: -80px;
    height: 100%;
    z-index: 1000;
    transition: left 0.3s;
  }

  .sidebar.open {
    left: 0;
  }

  .menu-toggle {
    display: block !important;
  }

  .task-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .task-actions {
    align-self: flex-end;
  }
}

.menu-toggle {
  display: none;
  margin-right: 15px;
  cursor: pointer;
}
</style>